import React, { useState } from "react";
import { Linking, StyleSheet } from "react-native";
import WebView from "react-native-webview";
import { fun, html_template } from "../../configs/commonStyle";
import { isAndroid, windowWidth } from "../../configs/platform";
import ImageViewerDialog from "../common/ImageViewerDialog";
import { View } from "react-native-ui-lib";
import { appStore } from "../../store";

/**
 * 高度自适应webview(这个必须全部或者部分位于第一屏，否则安卓会闪退)
 * @param label
 * @param style
 * @returns {JSX.Element}
 * @constructor
 */

const SpatacusAutoHeightWebView = ({ html }) => {
  const [wHeight, setWHeight] = useState(2);

  const onMessage = (event) => {
    try {
      logger("js回调", event.nativeEvent.data);
      if (!IsNullOrEmpty(event.nativeEvent.data)) {
        const action = JSON.parse(event.nativeEvent.data);
        logger("回调", action);
        if (action.type == "a" && action.url) {
          Linking.openURL(`${action.url}`).catch(Log);
        } else if (action.type == "img") {
          let pos = 0;
          for (let i = 0; i < action.images.length; i++) {
            if (action.images[i].url == action.url) {
              break;
            }
            pos++;
          }
          this.imageViewerDialog.show(action.images, pos);
        } else if (action.type == "setHeight") {
          if (!IsNullOrEmpty(action.height)) {
            logger("设置高度", action.height);
            setWHeight(action.height + 1);
          }
        }
      }
    } catch (error) {
    }
  };

  return (
    <View style={styles.container}>
      <WebView
        injectedJavaScript={fun}
        style={{
          width: windowWidth,
          height: wHeight,
          backgroundColor: "white",
        }}
        automaticallyAdjustContentInsets
        source={{ html: html_template.replace("#content#", html) }}
        decelerationRate="normal"
        scalesPageToFit
        javaScriptEnabled // 仅限Android平台。iOS平台JavaScript是默认开启的。
        domStorageEnabled // 适用于安卓
        scrollEnabled={false}
        showsVerticalScrollIndicator={false}
        onMessage={onMessage}
        onLoadStart={() => isAndroid() ? appStore.startFetch() : null}
        onLoadEnd={() => {
          if (isAndroid()) {
            appStore.finishFetch();
          }
        }}
      />
      <ImageViewerDialog ref={r => this.imageViewerDialog = r} />
    </View>
  );
};

export default SpatacusAutoHeightWebView;

const styles = StyleSheet.create({
  container: { flex: 1, backgroundColor: "white" },
});
